package com.toro.client.handler;

import com.toro.message.PingMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: HeartBeatClientHandler
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/12 19:17
 */
@Slf4j
public class HeartBeatClientHandler extends ChannelDuplexHandler {
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("客户端：{}离开",channel);
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("客户端：{}上线",channel);
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("客户端：{}下线",channel);
        super.channelInactive(ctx);
    }

    /**
     * 触发特殊事件
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (event.state() == IdleState.WRITER_IDLE) {
            PingMessage pingMessage = new PingMessage();
//            pingMessage.setSequenceId(250);
            ctx.writeAndFlush(pingMessage);
            log.debug("发送的心跳数据{}",pingMessage);
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("服务端：{}加入",channel);
        super.handlerAdded(ctx);
    }
}
